getFieldList();
function getFieldList(){
    $.ajax({
        url:config.url + "/getFieldList",
        dataType:'json',
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true,
        type:'GET' ,
        success:function(resp) {
            addOptionList(resp.data);
        },
        error:function() {
        }
    });
}
function addOptionList(arr){
    let str = ' <option value="">请选择</option>';
    for (let i = 0; i < arr.length; i++) {
        let a  = arr[i];
        str += `<option value="${a.id}">${a.fieldName}</option>`;
    }
    $('#picker6')[0].innerHTML = str;
}

getUserInfo();
function getUserInfo(){
    $.ajax({
        url:config.url + "/getUserInfo",
        dataType:'json',
        xhrFields: {
            withCredentials: true
        },
        headers:{
            "token":localStorage.getItem("token")
        },
        crossDomain: true,
        type:'GET' ,
        success:function(resp) {
            if(resp.data != null){
                $("#login-reg-btn")[0].innerHTML = "欢迎 " + resp.data;
            }else{
                $("#login-reg-btn")[0].innerHTML = "登录/注册";
            }
        },
        error:function() {
        }
    });
}

$('#picker3').picker();
function initPage(pageNo,totalCount,arr,fieldId){
    // 获取分页器实例对象
    var myPager = $('#myPager').data('zui.pager');
   //设置当前页码为 4，并同时设置记录总数为 100， 每页记录数目为 30
    myPager.set(pageNo, totalCount, 5);
    renderSubscribeList(arr,pageNo,fieldId);
}
$('#myPager').pager({
    onPageChange: function(state, oldState) {
        if (state.page !== oldState.page) {
            // console.log('页码从', oldState.page, '变更为', state.page);
            queryBtn(state.page);
        }
    }
});
var mapWrap = new Map();
var fieldIdTem;
function renderSubscribeList(arr,pageNo,fieldId1){
    //初始化分页器
    $('#myPager').css('display','flex');
    let map;
    if (arr.length != 0){
        //获取缓存
        map = jsonToMap(localStorage.getItem("answer"+arr[0].fieldId));
        //存入
        mapWrap.set(arr[0].fieldId,map);
    }
    var pageNum=(pageNo -1)*5;
    let str = `<div class="flex submitBtn-wrap"><button class="btn btn-success submitBtn" type="button" onclick="submitSubject(${arr[0].fieldId})">提交试卷</button></div>`;
    let b;
    for (let i = 0; i < arr.length; i++) {
        b  = arr[i];
        var c = pageNum + (i + 1);
        str += `<div class="item flex cons-info-item">
                    <div class="intro" onclick="testSubject(${c},${b.fieldId})">
                        <div id="name"><span>题目${c}：</span>${b.name}</div>
                        <hr>
                        <div class="flex subject1">
                            <div>
                                <div class="radio">
                                  <label>
                                    <input type="radio" name="radioOptionsExample${c}" value="A"> A. ${b.option1}
                                  </label>
                                </div>
                            </div>
                            <div>
                                <div class="radio">
                                  <label>
                                    <input type="radio" name="radioOptionsExample${c}" value="B"> B. ${b.option2}
                                  </label>
                                </div>
                            </div>
                        </div>
                        <div class="flex subject1">
                        <div>
                                <div class="radio">
                                  <label>
                                    <input type="radio" name="radioOptionsExample${c}" value="C"> C. ${b.option3}
                                  </label>
                                </div>
                             
                            </div>
                            <div>
                                <div class="radio">
                                  <label>
                                    <input type="radio" name="radioOptionsExample${c}" value="D"> D. ${b.option4}
                                  </label>
                                </div>
                            </div>
                        </div>
             

                    </div>
                 </div>`
    }

    //初始话试题
    $('#items-wrap')[0].innerHTML = str;


    if (map.get("fieldId") != null ){

        if (fieldIdTem == fieldId1){
            map.forEach((val,key) => {
                var field = map.get("fieldId");
                if (field == b.fieldId){
                    $("input[name=radioOptionsExample"+key+"][value="+val+"]").attr("checked",true);
                }
            });
        }else{
            let b1 = confirm("是否继续答题？");
            if (b1){
                map.forEach((val,key) => {
                    var field = map.get("fieldId");
                    if (field == b.fieldId){
                        $("input[name=radioOptionsExample"+key+"][value="+val+"]").attr("checked",true);
                    }
                });
            }else{
                //清理缓存
                localStorage.removeItem("answer");
            }
            fieldIdTem = fieldId1;
        }
    }
}

function testSubject(num,fieldId){
    let map = mapWrap.get(fieldId);
    map.set("fieldId",fieldId);
    var obj = document.getElementsByName('radioOptionsExample' + num);
    for(var i = 0;i < obj.length; i++){
        if(obj[i].checked){
            map.set(num,obj[i].value);
            //map转json
            console.log(MapTOJson(map));
        }
    }
    localStorage.setItem("answer"+fieldId, MapTOJson(map));
    // localStorage.
}

function MapTOJson(m) {
    var str = '{';
    var i = 1;
    m.forEach(function (item, key, mapObj) {
        if(mapObj.size == i){
            str += '"'+ key+'":"'+ item + '"';
        }else{
            str += '"'+ key+'":"'+ item + '",';
        }
        i++;
    });
    str +='}';
    return str;
}

function objToStrMap(obj){
    let strMap = new Map();
    if (obj != null){

        for (let k of Object.keys(obj)) {
            strMap.set(k,obj[k]);
        }
    }
    return strMap;
}
/**
 *json转换为map
 */
function  jsonToMap(jsonStr) {
    return objToStrMap(JSON.parse(jsonStr));
}

function submitSubject(fieldId){
    var score = 0;
    var map = mapWrap.get(fieldId);
    map.forEach((val,key) => {
            console.log(val)
        if (val == "A"){
            score += 5;
        }else if(val == "B"){
            score +=6;
        }else if(val == "C"){
            score +=8;
        }else if(val == "D"){
            score +=10;
        }
    })
    var username = parent.document.getElementById("login-reg-btn").innerText.split(" ")[1];

    $.ajax({
        url:config.url + "/subject/assessment",
        dataType:'json',
        xhrFields: {
            withCredentials: true
        },
        data:{
            fieldId:fieldId,
            score:score,
            username:username
        },
        crossDomain: true,
        type:'POST',
        success:function(resp) {
            if (resp.code == -1){
                localStorage.removeItem("answer"+fieldId);
                return alert(resp.msg)
            }
            alert("得分为：" + score +"，详细内容到我的报告查看");
            localStorage.removeItem("answer"+fieldId);
        },
        error:function() {
            alert("请先登录！");
        }
    });



}
function queryBtn(i){
    let fieldId = $('#picker6').val();
    if (fieldId == '' || fieldId == 0){
        alert('请选择领域');
        return;
    }
    $.ajax({
        url:config.url + "/subject/getList",
        dataType:'json',
        xhrFields: {
            withCredentials: true
        },
        data:{
            pageNo:i,
            fieldId:fieldId
        },
        crossDomain: true,
        type:'GET',
        success:function(resp) {
            var totalCount = resp.data.totalCount;
            initPage(resp.data.pageNo,totalCount,resp.data.list,fieldId);
        },
        error:function() {
        }
    });
}